package com.zhanghp.class01;

import static com.zhanghp.utils.CommonUtils.*;
import static java.lang.Math.*;
/**
 * @author zhanghp
 * @date 2023/8/1 17:37
 */
public class Code05_EqualProbabilityRandom {

    public static void main(String[] args) {
        verify(0.99);
    }

    /**
     * 你只能知道，x会以固定概率返回0和1，但是x的内容，你看不到！
     * <p>0返回的概率：p</p>
     * <p>1返回的概率：(1-p)</p>
     *
     * @return 0,1
     */
    public static class RandBox{
        double p;
        public RandBox(double p){
            this.p = p;
        }
        public int randBoxRandom(){
            return random() < p ? 0 : 1;
        }
    }

    /**
     * 利用固定概率返回0,1函数，实现等概率返回0,1
     * <p>
     * 实现原理：
     * <p>1:  p    p</p>
     * <p>2:  p  1-p</p>
     * <p>3: 1-p  p</p>
     * <p>4; 1-p 1-p</p>
     * <p>只取2,3两种情况揉</p>
     * </p>
     *
     * @return 0,1
     */
    public static int equalProbability(RandBox randBox){
        int var = 0;
        do {
            var = randBox.randBoxRandom();
        } while (var == randBox.randBoxRandom());
        return var;
    }

    /**
     * 验证
     *
     * @param p 固定概率返回0,1
     */
    public static void verify(double p){
        RandBox randBox = new RandBox(p);
        int count = 0;
        for (int i = 0; i < TEST_COUNT; i++) {
            if (equalProbability(randBox) == 0) {
                count ++;
            }
        }
        System.out.println(((double) count) / TEST_COUNT);
    }
}
